import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { routerRedux, Link } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select, Icon,
  Button, Dropdown, Menu, InputNumber,
  DatePicker, Modal, message, Badge, Table,
  Divider, Tag, Tree, Tooltip, Spin
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './StructureMaintenance.less';

const TreeNode = Tree.TreeNode;
/*
 组织架构维护界面
*/
const { Description } = DescriptionList;
const FormItem = Form.Item;
const { Option } = Select;

@connect(({ structure }) => ({
  structure,
}))
@Form.create()
export default class StructureMaintenance extends PureComponent {

  state = {
    currentBranch: null,
    modalVisible: false,
    isSetState: false,
    isFlag: false,//判断是否选中树节点
    selectedKeys: [],
    treeData: [],
    organizationName: '',
    jobsId: '',
    branchList: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'structure/fetch',
      callback: () =>{
        const { structure: { branchList } } = this.props;
        branchList&&
          this.setState({
            branchList: branchList,
            selectedKeys: [branchList[0].id],
            currentBranch: true
          })
          branchList&&
          dispatch({
            type: 'structure/jobs',
            payload: {
              branchId: branchList[0].id,
            },
          });
      }
    });
  }

  onSelect = (selectedKeys, info) => {
    
    if(selectedKeys){
      this.setState({
        selectedKeys: selectedKeys,
        currentBranch: true
      });
      this.props.dispatch({
        type: 'structure/jobs',
        payload: {
          branchId: selectedKeys[0],//Array.isArray(selectedKeys) ? selectedKeys[0] : selectedKeys,
        },
      });
    }  
  }

  handleAddJobs = () => {
    this.setState({
      modalVisible: true,
    });
  }

  handleMaintenance = () => {
    this.props.dispatch(routerRedux.push('/system/organization-edit'));
  }

  addRole = () => {
    this.props.dispatch(routerRedux.push('/system/role-list'));
  }

  handleModalOk = () => {
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        // console.log("this.state.selectedKeys",this.state.selectedKeys)
        if(values.positionName){
          this.props.form.resetFields();
          this.props.dispatch({
            type: 'structure/addJobs',
            payload: {
              branchId: this.state.selectedKeys[0],
              positionName: values.positionName,
              positionDesc: values.positionDesc,
            },
            callback: () => {
              this.props.dispatch({
                type: 'structure/jobs',
                payload: {
                  branchId: this.state.selectedKeys[0],
                },
              });
            },
          });
          this.setState({
            modalVisible: false,
          });
        }      
      }
    });
  }


  handleModalCancel = () => {
    this.setState({
      modalVisible: false,
    });
  }

  deleteJobs = (id) => {
    this.props.dispatch({
      type: 'structure/deleteJobs',
      payload: {
        postId: id,
      },
      callback: () => {
        this.props.dispatch({
          type: 'structure/jobs',
          payload: {
            branchId: this.state.selectedKeys[0],
          },
        });
      }
    })
  }

  renderTreeNodesChildren = (data) => {
    this.setState({
      treeData: data
    })
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode
            title={item.orgName}
            key={item.id}
            dataRef={item}
          >
            {this.renderTreeNodesChildren(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode
        key={item.id}
        dataRef={item}
        title={item.orgName} />;
    });
  }

  columns = [{
    title: '岗位名称',
    dataIndex: 'positionName',
    key: 'positionName',
    width: '20%',
  }, {
    title: '岗位描述',
    dataIndex: 'positionDesc',
    key: 'positionDesc',
    width: '60%',
  }, {
    title: '操作',
    dataIndex: 'id',
    key: 'id',
    render: (text, record) => (
      <Fragment>
        <Link to={`/system/jobs-details?id=${record.id}`}>详情</Link>
        <Divider type="vertical" />
        <a onClick={() => this.deleteJobs(record.id)}>删除</a>
      </Fragment>
    )
  }];

  render() {

    const { structure: { branchList, jobsList, loading, page, deleteJobsLoading } } = this.props;
    const { getFieldDecorator } = this.props.form;

    let defaultBranchId = branchList&&branchList[0]

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    
    return (
      <PageHeaderLayout title="组织架构维护">
        <Card
          bordered={false} >
          <DescriptionList style={{ marginBottom: 32 }} col={2}>
            <Row>
              <div className={styles.tableListOperator}>
                <Button style={{ marginBottom: 30 }} onClick={() => this.handleMaintenance()}>
                  维护组织架构
                </Button>
              </div>
            </Row>
          </DescriptionList>
          <Row>
            <Col span={6}>           
              <Tree
                showLine
                // defaultExpandParent
                autoExpandParent={true}
                defaultExpandAll={true}
                onSelect={this.onSelect}
                // expandedKeys={[this.state.branchList[0]&&this.state.branchList[0].id]}
                defaultSelectedKeys={[this.state.branchList[0]&&this.state.branchList[0].id]}
                selectedKeys={this.state.selectedKeys}
              >
                {branchList && this.renderTreeNodesChildren(branchList)}
              </Tree>
            </Col>
            <Col span={18}>
              {
                this.state.currentBranch &&
                <Card>
                  <Card
                    title="岗位列表"
                    bordered={false}
                    extra={
                      <p>
                        <Button icon="plus" type="primary" onClick={() => this.handleAddJobs()}>
                          添加岗位
                        </Button>
                      </p>
                    }
                  >
                    <Table
                      bordered
                      dataSource={jobsList}
                      columns={this.columns}
                      rowKey="id"
                      pagination={page}
                      loading={deleteJobsLoading}
                    />
                  </Card>
                </Card>
               } 
            </Col>
          </Row>
        </Card>
        <Modal
          title={'添加岗位'}
          visible={this.state.modalVisible}
          onOk={this.handleModalOk}
          confirmLoading={loading}
          onCancel={this.handleModalCancel}
        >
          <Form >
            <FormItem {...formItemLayout} label="岗位名称">
              {getFieldDecorator('positionName', {
                rules: [{
                  required: true, message: '请输入岗位名称',
                }],
              })(
                <Input placeholder="请输入岗位名称" />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="岗位描述">
              {getFieldDecorator('positionDesc')(
                <Input placeholder="请输入岗位描述" />
              )}

            </FormItem>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
